<script setup>
// 导入Element Plus组件
import { ref, onMounted, onUnmounted } from 'vue'
import {
  ElButton,
  ElCard,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElInputNumber,
  ElMessage,
  ElRow,
  ElCol,
  ElDivider,
  ElLoading
} from 'element-plus'

// 导入API服务
import { listSigning, getSigning, delSigning, addSigning, updateSigning } from "@/api/signing"

// 表单数据
const form = ref({
  flight: '',          // 航班
  contact: '',         // 联系方式
  passengerCount: 1,   // 出行人数
  departureCity: '',   // 出发地
  departureDate: '',   // 出行日期
  returnDate: '',      // 返回日期
  wechat: '',          // 微信号（非必填）
  hasAdult: '无'         // 是否有年满20周岁60周岁以下人员
})

// 加载状态
const loading = ref(false)
// 屏幕尺寸检测
const isSmallScreen = ref(false)

// 检测屏幕尺寸
const checkScreenSize = () => {
  isSmallScreen.value = window.innerWidth < 768
}

// 挂载时检测并监听窗口大小变化
onMounted(() => {
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

// 卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})

// 表单验证规则
const rules = {
  flight: [
    { required: true, message: '请输入航班号', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ],
  passengerCount: [
    { required: true, type: 'number', min: 1, message: '出行人数至少为1人', trigger: 'blur' }
  ],
  departureCity: [
    { required: true, message: '请选择出发地', trigger: 'change' }
  ],
  departureDate: [
    { required: true, message: '请选择出行日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value) {
          const today = new Date()
          today.setHours(0, 0, 0, 0)
          const oneWeekLater = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
          const selectedDate = new Date(value)
          if (selectedDate.getTime() < oneWeekLater.getTime()) {
            callback(new Error('出行日期必须是一周后或更晚'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  returnDate: [
    { required: true, message: '请选择返回日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.value.departureDate && new Date(value).getTime() <= new Date(form.value.departureDate).getTime()) {
          callback(new Error('返回日期必须晚于出行日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  hasAdult: [
    { required: true, message: '请选择是否有年满20周岁60周岁以下人员', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref(null)

// 常用城市列表
const cities = [
  { label: '北京', value: '北京' },
  { label: '上海', value: '上海' },
  { label: '广州', value: '广州' },
  { label: '深圳', value: '深圳' },
  { label: '杭州', value: '杭州' },
  { label: '成都', value: '成都' },
  { label: '南京', value: '南京' },
  { label: '武汉', value: '武汉' },
  { label: '西安', value: '西安' },
  { label: '重庆', value: '重庆' },
  { label: '天津', value: '天津' },
  { label: '苏州', value: '苏州' },
  { label: '长沙', value: '长沙' },
  { label: '青岛', value: '青岛' },
  { label: '郑州', value: '郑州' },
  { label: '宁波', value: '宁波' },
  { label: '厦门', value: '厦门' },
  { label: '大连', value: '大连' },
  { label: '济南', value: '济南' },
  { label: '合肥', value: '合肥' },
  { label: '福州', value: '福州' },
  { label: '昆明', value: '昆明' },
  { label: '沈阳', value: '沈阳' },
  { label: '长春', value: '长春' },
  { label: '哈尔滨', value: '哈尔滨' },
  { label: '石家庄', value: '石家庄' },
  { label: '太原', value: '太原' },
  { label: '呼和浩特', value: '呼和浩特' },
  { label: '南昌', value: '南昌' },
  { label: '南宁', value: '南宁' },
  { label: '海口', value: '海口' },
  { label: '贵阳', value: '贵阳' },
  { label: '拉萨', value: '拉萨' },
  { label: '兰州', value: '兰州' },
  { label: '西宁', value: '西宁' },
  { label: '银川', value: '银川' },
  { label: '乌鲁木齐', value: '乌鲁木齐' },
  { label: '东莞', value: '东莞' },
  { label: '佛山', value: '佛山' },
  { label: '无锡', value: '无锡' },
  { label: '温州', value: '温州' },
  { label: '泉州', value: '泉州' },
  { label: '南通', value: '南通' },
  { label: '常州', value: '常州' },
  { label: '徐州', value: '徐州' },
  { label: '唐山', value: '唐山' },
  { label: '烟台', value: '烟台' },
  { label: '潍坊', value: '潍坊' },
  { label: '临沂', value: '临沂' },
  { label: '洛阳', value: '洛阳' },
  { label: '襄阳', value: '襄阳' },
  { label: '宜昌', value: '宜昌' },
  { label: '岳阳', value: '岳阳' },
  { label: '衡阳', value: '衡阳' },
  { label: '株洲', value: '株洲' },
  { label: '赣州', value: '赣州' },
  { label: '九江', value: '九江' },
  { label: '芜湖', value: '芜湖' },
  { label: '蚌埠', value: '蚌埠' },
  { label: '嘉兴', value: '嘉兴' },
  { label: '湖州', value: '湖州' },
  { label: '绍兴', value: '绍兴' },
  { label: '金华', value: '金华' },
  { label: '台州', value: '台州' },
  { label: '镇江', value: '镇江' },
  { label: '扬州', value: '扬州' },
  { label: '泰州', value: '泰州' },
  { label: '盐城', value: '盐城' },
  { label: '淮安', value: '淮安' },
  { label: '宿迁', value: '宿迁' },
  { label: '连云港', value: '连云港' },
  { label: '舟山', value: '舟山' },
  { label: '衢州', value: '衢州' },
  { label: '丽水', value: '丽水' },
  { label: '淮北', value: '淮北' },
  { label: '淮南', value: '淮南' },
  { label: '马鞍山', value: '马鞍山' },
  { label: '铜陵', value: '铜陵' },
  { label: '安庆', value: '安庆' },
  { label: '黄山', value: '黄山' },
  { label: '滁州', value: '滁州' },
  { label: '阜阳', value: '阜阳' },
  { label: '宿州', value: '宿州' },
  { label: '六安', value: '六安' },
  { label: '亳州', value: '亳州' },
  { label: '池州', value: '池州' },
  { label: '宣城', value: '宣城' },
  { label: '莆田', value: '莆田' },
  { label: '三明', value: '三明' },
  { label: '漳州', value: '漳州' },
  { label: '南平', value: '南平' },
  { label: '龙岩', value: '龙岩' },
  { label: '宁德', value: '宁德' },
  { label: '景德镇', value: '景德镇' },
  { label: '萍乡', value: '萍乡' },
  { label: '新余', value: '新余' },
  { label: '鹰潭', value: '鹰潭' },
  { label: '吉安', value: '吉安' },
  { label: '宜春', value: '宜春' },
  { label: '抚州', value: '抚州' },
  { label: '上饶', value: '上饶' },
  { label: '淄博', value: '淄博' },
  { label: '枣庄', value: '枣庄' },
  { label: '东营', value: '东营' },
  { label: '济宁', value: '济宁' },
  { label: '泰安', value: '泰安' },
  { label: '威海', value: '威海' },
  { label: '日照', value: '日照' },
  { label: '莱芜', value: '莱芜' },
  { label: '德州', value: '德州' },
  { label: '聊城', value: '聊城' },
  { label: '滨州', value: '滨州' },
  { label: '菏泽', value: '菏泽' },
  { label: '邯郸', value: '邯郸' },
  { label: '邢台', value: '邢台' },
  { label: '保定', value: '保定' },
  { label: '张家口', value: '张家口' },
  { label: '承德', value: '承德' },
  { label: '沧州', value: '沧州' },
  { label: '廊坊', value: '廊坊' },
  { label: '衡水', value: '衡水' }
]
function formatDateToYYYYMMDD(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
// 提交表单
const submitForm = async () => {
  const loadingInstance = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
  try {
    form.value.departureDate = formatDateToYYYYMMDD(new Date(form.value.departureDate))
    form.value.returnDate = formatDateToYYYYMMDD(new Date(form.value.returnDate))
    await formRef.value.validate()
    loading.value = true
    const res = await addSigning(form.value)
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('表单提交成功！')
      formRef.value.resetFields()
      form.value.wechat = ''
    } else {
      ElMessage.error(res.message || '提交失败')
    }
    // const response = await flightApi.submitFlightInfo(form.value)
    // if (response.code === 0 || response.code === 200) {
    //   ElMessage.success('表单提交成功！')
    //   formRef.value.resetFields()
    // } else {
    //   ElMessage.error(response.message || '提交失败')
    // }
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
    loadingInstance.close()
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  ElMessage.info('表单已重置')
}
</script>

<template>
  <div class="app">
    <header class="header">
      <h1>信息登记</h1>
    </header>

    <main class="main">
      <ElCard class="form-card">
        <template #header>
          <div class="card-header">
            <span>请填写相关信息</span>
          </div>
        </template>

        <ElForm ref="formRef" :model="form" :rules="rules" :label-width="isSmallScreen ? '80px' : '120px'"
          :label-position="isSmallScreen ? 'top' : 'left'" status-icon class="responsive-form">
          

          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="24" :md="24">
              <ElFormItem label="联系方式" prop="contact">
                <ElInput v-model="form.contact" placeholder="请输入11位手机号码" maxlength="11" />
              </ElFormItem>
            </ElCol>
          </ElRow>

          <!-- 小屏幕下分两行，大屏幕分两列 -->
          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="12" :md="12">
              <ElFormItem label="出行人数" prop="passengerCount">
                <ElInputNumber v-model="form.passengerCount" :min="1" :max="20" style="width: 100%" />
              </ElFormItem>
            </ElCol>

            <!-- <ElCol :xs="24" :sm="12" :md="12">
              <ElFormItem label="从哪里出发" prop="departureCity">
                <ElSelect v-model="form.departureCity" placeholder="请选择出发城市" style="width: 100%">
                  <ElOption v-for="city in cities" :key="city.value" :label="city.label" :value="city.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol> -->
            <ElCol :xs="24" :sm="12" :md="12">
              <ElFormItem label="从哪里出发" prop="departureCity">
                <ElSelect v-model="form.departureCity" placeholder="请选择或输入出发城市" style="width: 100%" filterable 
                  allow-create
                  default-first-option 
                  >
                  <ElOption v-for="city in cities" :key="city.value" :label="city.label" :value="city.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="24" :md="24">
              <ElFormItem label="航班号" prop="flight">
                <ElInput v-model="form.flight" placeholder="如有中转，填写中转航班号" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <!-- 小屏幕下分两行，大屏幕分两列 -->
          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="12" :md="12">
              <ElFormItem label="出行日期" prop="departureDate">
                <ElDatePicker v-model="form.departureDate" type="date" placeholder="选择出行日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" :disabled-date="(time) => {
                    const today = new Date();
                    today.setHours(0, 0, 0, 0);
                    const oneWeekLater = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000);
                    // 禁用过去的日期和未来一周内的日期
                    return time.getTime() < today.getTime() - 8.64e7 || (time.getTime() >= today.getTime() && time.getTime() < oneWeekLater.getTime());
                  }" style="width: 100%" :popper-placement="isSmallScreen ? 'bottom' : 'bottom-start'"
                  :popper-append-to-body="!isSmallScreen" />
              </ElFormItem>
            </ElCol>

            <ElCol :xs="24" :sm="12" :md="12">
              <ElFormItem label="返回日期" prop="returnDate">
                <ElDatePicker v-model="form.returnDate" type="date" placeholder="选择返回日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" :disabled-date="(time) => {
                    if (!form.departureDate) return time.getTime() < Date.now() - 8.64e7
                    return time.getTime() < Date.now() - 8.64e7 || time.getTime() <= new Date(form.departureDate).getTime()
                  }" style="width: 100%" :popper-placement="isSmallScreen ? 'bottom' : 'bottom-start'"
                  :popper-append-to-body="!isSmallScreen" />
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="24" :md="24">
              <ElFormItem label="微信号">
                <ElInput v-model="form.wechat" placeholder="手机号无法添加微信填写" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow :gutter="20">
            <ElCol :xs="24" :sm="24" :md="24">
              <ElFormItem label="年满20周岁60周岁以下同行人员">
                <ElRadioGroup v-model="form.hasAdult">
                  <ElRadio label="1" value="有">有</ElRadio>
                  <ElRadio label="0" value="无">无</ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElDivider />

          <ElRow :gutter="20" class="form-actions">
            <ElCol :xs="24" :sm="24" :md="24" class="text-center">
              <ElButton type="primary" @click="submitForm" :loading="loading" class="submit-btn">提交</ElButton>
              <ElButton @click="resetForm" :disabled="loading" class="reset-btn">重置</ElButton>
            </ElCol>
          </ElRow>
        </ElForm>
      </ElCard>
    </main>
  </div>
</template>

<style scoped>
/* 基础样式 */
.app {
  min-height: 100vh;
  background-color: #f5f7fa;
  box-sizing: border-box;
  /* 新增：确保padding不影响整体尺寸 */
}

.header {
  background-color: #fff;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.main {
  padding: 30px 10px;
  /* 修改：左右内边距固定为10px */
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: calc(100vh - 88px);
  box-sizing: border-box;
}

.form-card {
  width: 100%;
  max-width: 600px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-sizing: border-box;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-actions {
  margin-top: 20px;
}

/* 统一所有表单组件100%宽度 */
.responsive-form .el-input,
.responsive-form .el-select,
.responsive-form .el-date-picker,
.responsive-form .el-input-number {
  width: 100% !important;
}

/* 按钮基础样式 */
.submit-btn {
  margin-right: 20px;
}

/* 响应式调整 - 平板设备 (768px - 1023px) */
@media (max-width: 1023px) {
  .header h1 {
    font-size: 22px;
  }

  .main {
    padding: 20px 10px;
    min-height: calc(100vh - 78px);
  }
}

/* 响应式调整 - 小平板和手机横屏 (480px - 767px) */
@media (max-width: 767px) {
  .header {
    padding: 15px 10px;
  }

  .header h1 {
    font-size: 20px;
  }

  .main {
    padding: 15px 10px;
    min-height: calc(100vh - 70px);
  }

  /* 标签顶对齐时，增加标签与内容的间距 */
  .el-form--label-top .el-form-item__label {
    margin-bottom: 8px !important;
    font-weight: 500;
  }

  /* 按钮间距减小 */
  .submit-btn {
    margin-right: 10px;
  }

  /* 城市选择器下拉框适配 */
  .el-select-dropdown {
    max-height: 300px !important;
    overflow-y: auto;
  }
}

/* 响应式调整 - 手机竖屏 (<= 479px) */
@media (max-width: 479px) {
  .header {
    padding: 12px 10px;
  }

  .header h1 {
    font-size: 18px;
  }

  .main {
    padding: 10px 5px;
    min-height: calc(100vh - 64px);
  }

  .form-card {
    padding: 0 10px;
    width: 100%;
    margin: 0 auto;
  }

  .el-form {
    padding: 15px 0;
  }

  .el-form-item {
    margin-bottom: 15px;
  }

  /* 小屏幕下按钮垂直排列 */
  .form-actions .el-button {
    display: block;
    width: 100%;
    margin-right: 0 !important;
    margin-bottom: 10px;
    padding: 12px 0;
  }

  /* 标签顶对齐时，进一步减小标签宽度 */
  .el-form--label-top .el-form-item__label {
    font-size: 14px;
    margin-bottom: 6px !important;
  }

  /* 优化输入框字体大小 */
  .el-input__inner,
  .el-select-dropdown__item,
  .el-date-picker__header-label,
  .el-date-picker__cell {
    font-size: 14px !important;
  }

  /* 日期选择器弹出层适配手机屏幕 */
  .el-date-picker__popper {
    width: 90% !important;
    max-width: 300px !important;
    left: 5% !important;
    right: 5% !important;
    transform: none !important;
    margin: 0 auto !important;
  }

  /* 修复城市选择器在小屏幕上溢出问题 */
  .el-select__popper {
    width: 90% !important;
    left: 5% !important;
    right: 5% !important;
    transform: none !important;
    max-height: 250px !important;
  }

  /* 移除body的默认边距，防止横向滚动 */
  body {
    margin: 0;
    padding: 0;
    overflow-x: hidden;
  }
}
</style>